/********************************
 * @FileName:     SessionContext.java
 * @Description:  SessionContext.java -
 * @Copyright:    Copyright(C) 2010-2011 mbool.com
 * @Company       MBOOL-TEAM zhangjiayi LTD.
 * @author:       zhangjiayi
 * @version       V1.0 
 * @Createdate:   2016-5-11 下午9:52:51
 *
 * All rights Reserved, Designed By MBOOL-TEAM
 *
 * Modification  History:
 * Date         Author        Version        Discription
 * -----------------------------------------------------------------------------------
 * 2016-5-11       zhangjiayi       1.0         TODO
 * Why & What is modified: <修改原因描述>
 *
 ********************************/
package com.rowline.admin.module.util.context;

import com.rowline.admin.module.util.constant.ContextContants;
import com.rowline.admin.module.util.domain.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * @ClassName: SessionContext
 * @Description: 会话的内容和上下文
 * @author: zhangjiayi
 * @date: 2016-5-11 下午9:52:51
 * 
 */
public class HttpSessionContext {

	static Logger log = LoggerFactory.getLogger(SessionContext.class);

	/**
	 * 全局获取HttpSession
	 * 
	 * @return
	 */
	private static HttpSession getHttpSession() {
		HttpServletRequest request = RequestContext.currentContext().getHttpRequest();
		if (null != request){
			try{
				return request.getSession();
			}catch(Exception e){
				log.error("获取session 错误：" + e.getClass() +" >>>> "+ e.getMessage());
			}
		}
		return null;
	}


	/**
	 * 添加session
	 */
	public static void setSession(String key, Object value) {
		if(null == getHttpSession()) return ;
		getHttpSession().setAttribute(key, value);
	}

	/**
	 * 获取当前session
	 */
	public static Object getSession(String key) {
		if(null == getHttpSession()) return null;
		return getHttpSession().getAttribute(key);
	}

	/**
	 * 当前登录用户员
	 */
	public static User getCurrentUser() {
		HttpSession session =  getHttpSession();
		if(session == null ) return null;
		Object user = session.getAttribute(ContextContants.CURRENT_LOGIN_SEESION_KEY);
		return null == user ? null : (User) user;

	}
	/**
	 * @Title:       登录用户名
	 * @Description: 
	 * @throws: 
	 * @return
	 * @date:	     2016-5-21 下午11:50:32
	 *
	 */
	public static String getCurrentUserName(){
		User user = getCurrentUser();
		if(null != user){
			return user.getName();
		}
		return null;
	}
	/**
	 * @Title:       设置当前登录用户
	 * @Description: 
	 * @throws: 
	 * @param user
	 * @date:	     2016-5-21 下午11:47:11
	 *
	 */
	public static void setCurrentUser(User user) {
		if (null != user){
			HttpSession session =  getHttpSession();
			if(session == null ) return ;
			session.setAttribute(ContextContants.CURRENT_LOGIN_SEESION_KEY, user);
		}
		else
			log.info("setCurrentUser is null ...");
	}
	
	public static void remove(String key) {
		HttpSession session =  getHttpSession();
		if(session == null ) return ;
		session.removeAttribute(key);
	}
	
}
